/**
 * @Description
 */

public class MySingleList {

    public class List {
        public List next;
        public int val;

        public List(int val) {
            this.val = val;
        }
    }
    public List head;

    List Node1 = new List(1);
    List Node2 = new List(2);
    List Node3 = new List(3);
    List Node4 = new List(4);

    public void crateList() {
        Node1.next = Node2;
        Node2.next = Node3;
        Node3.next = Node4;

        this.head = Node1;
    }

    public void show() {
        List cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }
    //反转一个单链表
    public List reserveLast(){
        if(head==null){
            return head;
        }
        List cur = head.next;
        head.next = null;
        while(cur!=null){
            //存放好将要移动的元素地址
            List curN = cur.next;
            cur.next = head;
            head = cur;
            cur = curN;
        }
        return head;
    }
    public int size(){
        List cur = head;
        int count = 0;
        while(cur!=null){
            count++;
        }
        return count;
    }
    public List findMiddleNode(){
        List cur = head;
        int len = size();
        int count = 0;
        int middle = size()/2;
        while(count!=middle){
            cur = cur.next;
            count++;
        }
        return cur;
    }
    public List findMiddleNode2(){
        List slow = head;
        List fast = head;
        //条件不能反
        while(fast!=null&&fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    public List find(int k){
        int len = size();
        int count = 0;
        List cur = head;
        while(count!=(len-k)){
            cur = cur.next;
            count++;
        }
        return cur;
    }
    public int kthToLast( int k) {
        if(head==null){
            return -1;
        }
        if(k<0||k>size()){
            return -1;
        }
        List cur = find(k).next;
        return cur.val;
    }

}
